import { SyncOutlined } from '@ant-design/icons-vue'
import {
  Button,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Space,
  Spin,
  TabPane,
  Tabs,
  Textarea,
  TypographyText
} from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { commonApi, commonMenuApi, marketingApi } from '@/apis'
import { YxGiftGoodsItem, YxGiftSkuItem } from '@/apis/marketingTypes'
import {
  ProEditor,
  ProEditorProps,
  ProEditorRef,
  ProTable,
  ProTableProps,
  ProTableRef
} from '@/components'
import UploadFile from '@/components/UploadFile'
import { FILE_TYPE } from '@/components/UploadFile/types'
import { useBack, useDialog } from '@/hooks'
import { isValueEmpty } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

export default defineComponent({
  name: 'YxEditGiftGoods',
  setup() {
    const { showConfirm } = useDialog()
    const activeTab = ref(1)
    const loading = ref(false)
    const route = useRoute()
    const goodsData = ref({} as YxGiftGoodsItem)
    const showSkuEditDialog = ref(false)
    const optionSkuItemCur = ref({} as YxGiftSkuItem)
    const optionSkuItemRefCur = ref({} as YxGiftSkuItem)
    const selectLabelList = ref([] as any[])
    const selectExpressList = ref([] as any[])
    const { handleCancel } = useBack('refreshXyGoodsList')

    const submitLoading = ref(false)
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: 500,
      options: {
        border: true,
        align: 'center',
        columns: [
          {
            title: '商品ERP货号',
            field: 'erpSpecNo'
          },
          {
            title: '商品名称',
            field: 'name'
          },
          {
            title: '图片',
            field: 'imgUrl',
            width: 100,
            slots: {
              default: 'image'
            }
          },
          {
            title: '起购量',
            field: 'initQuantity'
          },
          {
            title: '增量',
            field: 'incrQuantity'
          },
          {
            title: '库存',
            field: 'stock'
          },
          {
            title: 'ERP库存',
            slots: {
              default: 'erpStock'
            }
          },
          {
            title: '市场价格',
            field: 'marketPrice'
          },
          {
            title: '销售价格',
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 120
          }
        ]
      }
    } as ProTableProps)
    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '300px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data

              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)

    onMounted(() => {
      getLabelAndExpressList()
    })

    //获取优惠券和标签
    async function getLabelAndExpressList() {
      try {
        loading.value = true
        selectLabelList.value = await commonMenuApi.getSelectLabelList()
        selectExpressList.value =
          await marketingApi.getSelectExpressTempleteList()
        loading.value = false
        getDetail()
      } catch {
        handleCancel()
      }
    }

    //获取详情
    async function getDetail() {
      try {
        loading.value = true
        const data = await marketingApi.getGoodsDetail(route.query.id)
        editorConfig.value.editorHtml = data.description
        editorConfig.value.editorVisible = true
        Object.assign(goodsData.value, data)
        if (!goodsData.value.transitType && goodsData.value.transitType != 0) {
          goodsData.value.transitType = 0
        }
        loading.value = false
      } catch (e) {
        handleCancel()
      }
    }

    //确定
    async function confirm() {
      if (!goodsData.value.name) {
        message.error('请输入商品主标题')
        return
      }
      if (!goodsData.value.mainImg) {
        message.error('请上传商品主图')
        return
      }
      goodsData.value.description = editorRef.value.editor.getHtml()
      for (const skuItem of goodsData.value.goodsSpecs) {
        for (const i in skuItem) {
          if (isValueEmpty(skuItem[i]) && i != 'loading') {
            message.error('请完善商品规格信息')
            return
          }
        }
      }
      if (goodsData.value.transitType == 0 && !goodsData.value.transitId) {
        message.error('请选择运费模板')
        return
      }
      if (
        goodsData.value.transitType == 1 &&
        !goodsData.value.transitFee &&
        goodsData.value.transitFee != 0
      ) {
        message.error('请输入运费价格')
        return
      }
      try {
        submitLoading.value = true
        goodsData.value.goodsProperty = 1
        await marketingApi.editGoods(goodsData.value)
        handleCancel()
      } finally {
        submitLoading.value = false
      }
    }

    //上一步/下一步
    function changeTab(isNext: boolean) {
      if (isNext) {
        activeTab.value++
      } else {
        activeTab.value--
      }
    }

    //sku编辑
    function editSku(item: YxGiftSkuItem) {
      Object.assign(optionSkuItemCur.value, item)
      optionSkuItemRefCur.value = item
      showSkuEditDialog.value = true
    }

    function confirmEditSku() {
      for (const i in optionSkuItemCur.value) {
        if (isValueEmpty(optionSkuItemCur.value[i]) && i != 'loading') {
          message.error('请完善商品规格信息')
          return
        }
      }
      Object.assign(optionSkuItemRefCur.value, optionSkuItemCur.value)
      showSkuEditDialog.value = false
    }

    //sku禁用启用
    function changeSkuStatus(item: YxGiftSkuItem) {
      showConfirm({
        content: item.status == 1 ? '确认禁用该规格？' : '确认启该规格？',
        onOk: async () => {
          try {
            await marketingApi.upDownSku(item.id)
            const skuItem = goodsData.value.goodsSpecs.find(
              sku => sku.id == item.id
            )
            if (item.status == 1) {
              skuItem!.status = 0
            } else {
              skuItem!.status = 1
            }
          } catch (error) {}
        }
      })
    }

    //同步erp库存
    async function syncErpStock(item: YxGiftSkuItem) {
      if (!item.warehouseNo) {
        message.error('请先输入仓库编码')
        return
      }
      try {
        item.loading = true
        item.erpStock = await marketingApi.syncSkuErpStock(item.id)
      } finally {
        item.loading = false
      }
    }

    return {
      activeTab,
      selectLabelList,
      selectExpressList,
      tableConfig,
      loading,
      goodsData,
      editorRef,
      editorConfig,
      submitLoading,
      showSkuEditDialog,
      optionSkuItemCur,
      changeTab,
      editSku,
      changeSkuStatus,

      confirm,
      confirmEditSku,
      handleCancel,
      syncErpStock
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <Tabs v-model:activeKey={this.activeTab}>
            <TabPane key={1} tab="基本信息">
              <Form labelCol={{ span: 2 }}>
                <FormItem label="商品主标题" required>
                  <Input
                    maxlength={60}
                    v-model:value={this.goodsData.name}
                    placeholder="请输入"
                    style={{ width: '300px' }}
                  />
                </FormItem>
                <FormItem label="商品副标题">
                  <Textarea
                    v-model:value={this.goodsData.subTitle}
                    placeholder="请输入"
                    style={{ width: '300px' }}
                  />
                </FormItem>
                <FormItem label="商品属性" required>
                  <RadioGroup
                    v-model:value={this.goodsData.goodsPlatform}
                    defaultValue={0}
                  >
                    <Radio checked value={0}>
                      {'实物'}
                    </Radio>
                    <Radio checked value={1}>
                      {'轻姿颜'}
                    </Radio>
                  </RadioGroup>
                </FormItem>
                <FormItem label="设置标签">
                  <Input
                    v-model:value={this.goodsData.label}
                    placeholder="请输入"
                    style={{ width: '300px' }}
                  ></Input>
                </FormItem>
                <FormItem label="商品主图" required>
                  <UploadFile v-model={[this.goodsData.mainImg, 'urls']}>
                    上传图片
                  </UploadFile>
                </FormItem>
                <FormItem label="商品轮播图">
                  <UploadFile
                    maxLength={5}
                    v-model={[this.goodsData.banner, 'urls']}
                  >
                    上传图片
                  </UploadFile>
                </FormItem>
                <FormItem label="商品视频">
                  <div style={{ width: '400px' }}>
                    <UploadFile
                      fileType={FILE_TYPE.VIDEO}
                      v-model={[this.goodsData.video, 'urls']}
                    >
                      <Button>上传视频</Button>
                    </UploadFile>
                  </div>
                </FormItem>
                <FormItem label="商品详情信息">
                  <ProEditor ref="editorRef" {...this.editorConfig} />
                </FormItem>
                <FormItem label="虚拟销量">
                  <InputNumber
                    placeholder="请输入"
                    v-model:value={this.goodsData.saleNum}
                    min={0}
                    maxlength={10}
                    style={{ width: '300px' }}
                  />
                </FormItem>
                <FormItem>
                  <Button
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={this.handleCancel}
                  >
                    取消
                  </Button>
                  <Button
                    type="primary"
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={() => {
                      this.changeTab(true)
                    }}
                  >
                    下一步
                  </Button>
                </FormItem>
              </Form>
            </TabPane>
            <TabPane key={2} tab="商品规格">
              <div>
                <ProTable
                  data={this.goodsData.goodsSpecs}
                  ref="tableRef"
                  v-slots={{
                    image: ({ row }) => <Image src={row.imgUrl}></Image>,
                    status: ({ row }) => {
                      return (
                        <Space>
                          {row.status == 0 ? (
                            <TypographyText type="danger">下架</TypographyText>
                          ) : (
                            <TypographyText type="success">上架</TypographyText>
                          )}
                        </Space>
                      )
                    },
                    salePrice: ({ row }) => {
                      return (
                        <Space>
                          {handlePrice(row.salePrice, row.saleGold)}
                        </Space>
                      )
                    },
                    erpStock: ({ row }) => {
                      return (
                        <Space>
                          {row.erpStock || 0}
                          <SyncOutlined
                            spin={row.loading}
                            onClick={() => {
                              this.syncErpStock(row)
                            }}
                          />
                        </Space>
                      )
                    },
                    operation: ({ row }) => (
                      <Space>
                        <Button
                          type="link"
                          size="small"
                          onClick={() => this.editSku(row)}
                        >
                          编辑
                        </Button>
                        <Button
                          type="link"
                          size="small"
                          onClick={() => this.changeSkuStatus(row)}
                        >
                          {row.status === 0 ? '上架' : '下架'}
                        </Button>
                      </Space>
                    )
                  }}
                  {...this.tableConfig}
                />
                <FormItem>
                  <Button
                    type="primary"
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={() => {
                      this.changeTab(false)
                    }}
                  >
                    上一步
                  </Button>
                  <Button
                    type="primary"
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={() => {
                      this.changeTab(true)
                    }}
                  >
                    下一步
                  </Button>
                </FormItem>
              </div>
            </TabPane>
            <TabPane key={3} tab="物流信息">
              <Form labelCol={{ span: 2 }}>
                <FormItem label="运费" required>
                  <RadioGroup v-model:value={this.goodsData.transitType}>
                    <Radio value={0}>{'按照运费模板'}</Radio>
                    <Radio value={1}>{'按照固定金额'}</Radio>
                  </RadioGroup>
                </FormItem>
                <FormItem
                  label="运费模板"
                  required
                  placeholder="请选择"
                  v-show={this.goodsData.transitType == 0}
                >
                  <Select
                    v-model:value={this.goodsData.transitId}
                    style={{ width: '300px' }}
                  >
                    {this.selectExpressList.map(val => (
                      <SelectOption value={val.id}>{val.name}</SelectOption>
                    ))}
                  </Select>
                </FormItem>
                <FormItem
                  label="运费价格"
                  required
                  v-show={this.goodsData.transitType == 1}
                >
                  <InputNumber
                    placeholder="请输入"
                    v-model:value={this.goodsData.transitFee}
                    min={0}
                    precision={2}
                    maxlength={10}
                    style={{ width: '300px' }}
                  />
                  <p style={{ marginTop: '10px', color: '#888' }}>
                    每件商品的运费，输入0即代表包邮
                  </p>
                </FormItem>
                <FormItem>
                  <Button
                    type="primary"
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={() => {
                      this.changeTab(false)
                    }}
                  >
                    上一步
                  </Button>
                  <Button
                    type="primary"
                    style={{ marginTop: '30px', marginLeft: '90px' }}
                    onClick={this.confirm}
                  >
                    完成
                  </Button>
                </FormItem>
              </Form>
            </TabPane>
          </Tabs>
        </Spin>

        <Modal
          v-model:visible={this.showSkuEditDialog}
          title={'编辑'}
          onOk={this.confirmEditSku}
          destroyOnClose
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'图片'} required>
              <UploadFile v-model={[this.optionSkuItemCur.imgUrl, 'urls']}>
                上传图片
              </UploadFile>
            </FormItem>
            <FormItem label={'起订量'} required>
              <InputNumber
                v-model:value={this.optionSkuItemCur.initQuantity}
                placeholder="请输入"
                min={0}
                maxlength={10}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'增量'} required>
              <InputNumber
                v-model:value={this.optionSkuItemCur.incrQuantity}
                placeholder="请输入"
                min={0}
                maxlength={10}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'库存'} required>
              <InputNumber
                v-model:value={this.optionSkuItemCur.stock}
                placeholder="请输入"
                min={0}
                maxlength={10}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'市场价'} required>
              <InputNumber
                v-model:value={this.optionSkuItemCur.marketPrice}
                placeholder="请输入"
                min={0}
                maxlength={10}
                precision={2}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'销售价格'} required>
              <Space>
                {'现金'}
                <InputNumber
                  v-model:value={this.optionSkuItemCur.salePrice}
                  placeholder="请输入"
                  min={0}
                  maxlength={10}
                  precision={2}
                  style={{ width: '100px' }}
                />
              </Space>
            </FormItem>
            <FormItem label={'仓库编码'} required>
              <Input
                v-model:value={this.optionSkuItemCur.warehouseNo}
                placeholder="请输入"
                style={{ width: '200px' }}
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
